package com.liang.maogouyuyin.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.liang.maogouyuyin.R;
import com.liang.maogouyuyin.databinding.FragmentHomeBinding;
import com.liang.maogouyuyin.ui.adapter.HomeFragmentAdapter;
import com.liang.maogouyuyin.utils.lzy.PermissionUtils;
import com.google.android.material.tabs.TabLayoutMediator;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

public class HomeFragment extends Fragment {
    FragmentHomeBinding binding;
    @SuppressLint("StaticFieldLeak")
    public static  FrameLayout mFeedContainer;
    private HomeFragmentAdapter adapter;
    private MediaRecorder recorder;

    private String tempPath;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initData();
        initView();
        initClick();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        recorder.release();
        if (requireContext().getCacheDir().exists()) {
            File[] list = requireContext().getCacheDir().listFiles();
            if (list != null)
                for (File file : list) {
                    file.delete();
                }
        }
        super.onDestroy();
    }

    private void initData() {
        recorder = new MediaRecorder();
    }

    private void initView() {
        adapter = new HomeFragmentAdapter(requireActivity());
        binding.homeViewPager.setAdapter(adapter);
        binding.homeViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        binding.homePetRecorderText.setText(getString(R.string.home_cat_recorder));
                        break;
                    case 1:
                        binding.homePetRecorderText.setText(getString(R.string.home_dog_recorder));
                }
            }
        });

        new TabLayoutMediator(binding.homeTabLayout, binding.homeViewPager, (tab, position) -> {
            switch (position) {
                case 0:
                    tab.setText(getString(R.string.home_cat_translate));
                    break;
                case 1:
                    tab.setText(getString(R.string.home_dog_translate));
            }
        }).attach();
    }

    @SuppressLint({"ClickableViewAccessibility", "NotifyDataSetChanged"})
    private void initClick() {
        binding.homePetRecorder.setOnTouchListener((v, event) -> {
            if (XXPermissions.isGranted(requireContext(), Manifest.permission.RECORD_AUDIO)) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        binding.homePetRecorder.setScaleX(0.8f);
                        binding.homePetRecorder.setScaleY(0.8f);
                        //设置音源为麦克风
                        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                        //设置输出格式
                        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                        //设置音频编码器
                        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                        recorder.setOutputFile(getOutputFilePath());
                        try {
                            recorder.prepare();
                            recorder.start();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        binding.homePetRecorder.setScaleX(1f);
                        binding.homePetRecorder.setScaleY(1f);
                        new Handler(Looper.getMainLooper()).postDelayed(() -> {
                            recorder.stop();
                            TranslateFragment fragment = adapter.getFragment(binding.homeViewPager.getCurrentItem());
                            fragment.addPetTranslateView(tempPath);
                            adapter.notifyDataSetChanged();
                        }, 400);
                }
            } else if (event.getAction() == MotionEvent.ACTION_DOWN){
                PermissionUtils.INSTANCE.tryToDoSomethingWithCheckPermissionAndCode(
                        requireContext(),
                        new String[] {Manifest.permission.RECORD_AUDIO},
                        1,
                        "没有权限将无法正常使用功能",
                        () -> null
                );
            }
            return true;
        });

        binding.homeMasterRecorder.setOnTouchListener((v, event) -> {
            if (XXPermissions.isGranted(requireContext(), Manifest.permission.RECORD_AUDIO)) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        binding.homeMasterRecorder.setScaleX(0.8f);
                        binding.homeMasterRecorder.setScaleY(0.8f);
                        //设置音源为麦克风
                        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                        //设置输出格式
                        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
                        //设置音频编码器
                        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
                        recorder.setOutputFile(getOutputFilePath());
                        try {
                            recorder.prepare();
                            recorder.start();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        binding.homeMasterRecorder.setScaleX(1f);
                        binding.homeMasterRecorder.setScaleY(1f);
                        new Handler(Looper.getMainLooper()).postDelayed(() -> {
                            recorder.stop();
                            TranslateFragment fragment = adapter.getFragment(binding.homeViewPager.getCurrentItem());
                            fragment.addMasterTranslateView(tempPath);
                            adapter.notifyDataSetChanged();
                        }, 400);
                }
            } else if (event.getAction() == MotionEvent.ACTION_DOWN){
                PermissionUtils.INSTANCE.tryToDoSomethingWithCheckPermissionAndCode(
                        requireContext(),
                        new String[] {Manifest.permission.RECORD_AUDIO},
                        1,
                        "没有权限将无法正常使用功能",
                        () -> null
                );
            }
            return true;
        });
    }

    private String getOutputFilePath() {
        File file = new File(requireContext().getCacheDir(), Calendar.getInstance().getTimeInMillis() + ".m4a");
        tempPath = file.getAbsolutePath();
        return tempPath;
    }
}